﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Web;
using up7.db.biz;
using up7.db.model;
using up7.db.utils;
using up7.filemgr.app;
using up7.db.database.up7.sql;

namespace up7.api.filemgr
{
    public partial class f_create : WebBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            string pid = this.reqStr("pid");
            string pidRoot = this.reqStr("pidRoot");
            string md5 = this.reqStr("md5");
            string id = this.reqStr("id");
            string uid = this.reqStr("uid");
            string lenLoc = this.reqStr("lenLoc");
            string sizeLoc = this.reqStr("sizeLoc");
            string blockSize = this.reqStr("blockSize");
            string callback = this.reqStr("callback");
            string pathLoc = this.reqStrDecode("pathLoc");
            string pathRel = this.reqStrDecode("pathRel");

            if (string.IsNullOrEmpty(pid)) pid = string.Empty;
            if (string.IsNullOrEmpty(pidRoot)) pidRoot = pid;

            //参数为空
            if (string.IsNullOrEmpty(uid)
                || string.IsNullOrEmpty(sizeLoc))
            {
                Response.Write(callback + "({\"value\":null})");
                return;
            }

            FileInf fileSvr = new FileInf();
            fileSvr.fdChild = false;
            fileSvr.uid = uid;//将当前文件UID设置为当前用户UID
            fileSvr.id = id;
            fileSvr.pid = pid;
            bool isRootFile = pathRel == "/";
            fileSvr.fdChild = !isRootFile;
            fileSvr.pidRoot = pidRoot;
            fileSvr.nameLoc = Path.GetFileName(pathLoc);
            fileSvr.pathLoc = pathLoc;
            fileSvr.pathRel = PathTool.combin(pathRel, fileSvr.nameLoc);
            fileSvr.lenLoc = Convert.ToInt64(lenLoc);
            fileSvr.sizeLoc = sizeLoc;
            fileSvr.deleted = false;
            fileSvr.md5 = md5;
            fileSvr.nameSvr = fileSvr.nameLoc;
            fileSvr.blockSize = int.Parse(blockSize);//块大小

            //所有单个文件均以uuid/file方式存储
            PathGuidBuilder pb = new PathGuidBuilder();
            fileSvr.pathSvr = pb.genFile(fileSvr.uid, fileSvr.id, fileSvr.nameLoc);

            SqlFile.build().Add(fileSvr);

            //触发事件
            up7_biz_event.file_create(fileSvr);

            string jv = JsonConvert.SerializeObject(fileSvr);
            jv = HttpUtility.UrlEncode(jv);
            jv = jv.Replace("+", "%20");
            string json = callback + "({\"value\":\"" + jv + "\",\"ret\":true})";//返回jsonp格式数据。
            this.toContent(json);
        }
    }
}